# 该程序每30分钟运行一次，测试B站热搜多久变更一次。
import requests
import json
import datetime
import pandas as pd
import os

workPath = os.getcwd()

url = "https://api.bilibili.com/x/web-interface/search/square?limit=50"
r = requests.get(url)

hotSearchWord = r.json()['data']['trending']['list']
today = datetime.datetime.today()

hotSearchWord_list = []
for i in hotSearchWord:
    hotSearchWord_list.append(i)

# 写入日期信息
for i in range(len(hotSearchWord_list)):
    hotSearchWord_list[i]['date'] = today

df = pd.DataFrame(hotSearchWord_list)

# 格式化icon
def format_icon(url):
    if url == "http://i0.hdslb.com/bfs/feed-admin/e9e7a2d8497d4063421b685e72680bf1cfb99a0d.png":
        return "热"
    elif url == "http://i0.hdslb.com/bfs/feed-admin/4d579fb61f9655316582db193118bba3a721eec0.png":
        return "新"
    else:
        return "None"
df['icon']=list(map(format_icon,df['icon']))

# 保存本地
df.to_csv('/home/ubuntu/0000/b_hotSearch/data/B热搜更新记录.csv',mode='a', header=False)
